<template>
  <div class="q-pa-md">
    <q-table
      :rows="parametersList"
      :columns="columns"
      row-key="name"
      class="no-border-radius full-height"
      :class="
        ui.isDark
          ? 'my-sticky-header-table-black'
          : 'my-sticky-header-table-white'
      "
      :pagination="{ rowsPerPage: 0 }"
      :dark="ui.isDark"
    >
      <template v-slot:top-right>
        <div class="row q-gutter-x-md items-center">
          <q-select
            outlined
            dense
            v-model="parameter"
            :options="options"
            :label="$t('OsParameter.配置项目')"
            style="min-width: 150px; max-width: 200px"
            :dark="ui.isDark"
          />
          <q-btn
            :label="$t('OsParameter.撤销更改')"
            :class="ui.btnClass"
            color="primary"
            size="md"
            v-if="modified"
            @click="resets"
          />
        </div>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th auto-width />
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>

      <template v-slot:body="props">
        <q-tr :props="props" @click="props.expand = !props.expand">
          <q-td auto-width>
            <q-btn
              size="sm"
              color="accent"
              round
              dense
              @click="props.expand = !props.expand"
              :icon="props.expand ? 'keyboard_arrow_up' : 'keyboard_arrow_down'"
              :class="ui.btnClass"
            />
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.value }}
          </q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
            <div class="text-center q-pa-sm">
              <q-toggle
                color="blue"
                v-model="props.row.value"
                v-if="props.row.type === 'bool'"
                :label="$t('OsParameter.参数设置')"
                @click="setConfiguration(props.row)"
                :dark="ui.isDark"
              />
              <q-input
                v-model="props.row.value"
                :label="$t('OsParameter.参数设置')"
                @blur="setConfiguration(props.row)"
                filled
                v-else-if="props.row.type === 'str'"
                :dark="ui.isDark"
              />
              <q-input
                :dark="ui.isDark"
                filled
                type="number"
                v-model="props.row.value"
                :label="
                  $t('OsParameter.参数设置') +
                  ':' +
                  props.row.min +
                  '~' +
                  props.row.max
                "
                lazy-rules
                @blur="setConfiguration(props.row)"
                v-else-if="props.row.type === 'int'"
                ref="inputRef"
                :rules="[
                  (val) =>
                    Number(val) <= Number(props.row.max) ||
                    $t('OsParameter.请按照参数范围设置'),
                  (val) =>
                    Number(val) >= Number(props.row.min) ||
                    $t('OsParameter.请按照参数范围设置'),
                ]"
              />
              <q-input
                v-model="props.row.value"
                type="number"
                :dark="ui.isDark"
                :label="
                  $t('OsParameter.参数设置') +
                  ':' +
                  props.row.min +
                  '~' +
                  props.row.max
                "
                filled
                @blur="setConfiguration(props.row)"
                v-else-if="props.row.type === 'double'"
                mask="#.###"
                ref="inputRef"
                :rules="[
                  (val) =>
                    Number(val) <= Number(props.row.max) ||
                    $t('OsParameter.请按照参数范围设置'),
                  (val) =>
                    Number(val) >= Number(props.row.min) ||
                    $t('OsParameter.请按照参数范围设置'),
                ]"
              />
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:bottom>
        <div class="full-width">
          <div class="q-gutter-x-md float-right">
            <q-btn
              :label="$t('OsParameter.临时修改')"
              :class="ui.btnClass"
              @click="setParameter(false)"
            />
            <q-btn
              :label="$t('OsParameter.永久修改')"
              :class="ui.btnClass"
              @click="update"
            />
          </div>
        </div>
      </template>
    </q-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";
import { useFunctionsStore } from "stores/functions";

const $t = useI18n().t;
const columns = [
  { name: "name", label: $t("OsParameter.名称"), align: "left", field: "name" },
  {
    name: "value",
    label: $t("OsParameter.当前值"),
    align: "left",
    field: "value",
  },
  {
    name: "description",
    label: $t("OsParameter.参数说明"),
    align: "left",
    field: "description",
  },
];
const ui = useUiStore();
const $q = useQuasar();
const inputRef = ref(null);
// 配置集合
const parametersList = ref([]);
// 根节点
const parameter = ref("");
// 节点名称列表
const options = ref([]);
const origin = ref([]);

onMounted(() => {
  api
    .post(useAPIStore().amrUrl + "ros/call", [useFunctionsStore().osRole], {
      params: { service: "/config_center/list" },
    })
    .then((rs) => {
      options.value = rs.data.values.names;
      parameter.value = rs.data.values.names[rs.data.values.names.length - 1];
    });
});

watch(parameter, (value) => {
  if (!value) return;
  api
    .post(useAPIStore().amrUrl + "ros/call", [parameter.value], {
      params: { service: "/config_center/get" },
    })
    .then((rs) => {
      parametersList.value = rs.data.values.parameters;
      for (let i = 0; i < parametersList.value.length; i++) {
        if (parametersList.value[i].type === "bool") {
          parametersList.value[i].value = JSON.parse(
            parametersList.value[i].value
          );
        }
      }
      origin.value = JSON.parse(JSON.stringify(parametersList.value));
    });
});

// 重载配置
function load() {
  const list = [];
  for (let i = 0; i < parametersList.value.length; i++) {
    const obj = {};
    obj.id = parametersList.value[i].id;
    if (parametersList.value[i].type === "bool") {
      obj.value = String(parametersList.value[i].value);
    } else {
      obj.value = parametersList.value[i].value;
    }
    list.push(obj);
  }
  api
    .post(useAPIStore().amrUrl + "ros/call", [parameter.value, list], {
      params: { service: "/config_center/set" },
    })
    .then((rs) => {
      if (rs.data.values.success) {
        api
          .post(useAPIStore().amrUrl + "ros/call", [parameter.value], {
            params: { service: "/config_center/dump" },
          })
          .then((rs) => {
            if (rs.data.values.success) {
              $q.notify({
                type: "positive",
                message: $t("OsParameter.撤销成功"),
              });
            } else {
              $q.notify({
                type: "warning",
                message: $t("OsParameter.撤销失败"),
              });
            }
          });
      } else {
        $q.notify({ type: "warning", message: $t("OsParameter.撤销失败") });
      }
    });
}
// 保存配置
// eslint-disable-next-line no-unused-vars
function update() {
  setParameter(true);
}
// 设置配置
function setParameter(state) {
  const list = [];
  for (let i = 0; i < parametersList.value.length; i++) {
    const obj = {};
    obj.id = parametersList.value[i].id;
    if (parametersList.value[i].type === "bool") {
      obj.value = String(parametersList.value[i].value);
    } else {
      obj.value = parametersList.value[i].value;
    }
    list.push(obj);
  }
  api
    .post(useAPIStore().amrUrl + "ros/call", [parameter.value, list], {
      params: { service: "/config_center/set" },
    })
    .then((rs) => {
      if (rs.data.values.success) {
        if (state) {
          api
            .post(useAPIStore().amrUrl + "ros/call", [parameter.value], {
              params: { service: "/config_center/dump" },
            })
            .then((rs) => {
              if (rs.data.values.success) {
                $q.notify({
                  type: "positive",
                  message: $t("OsParameter.永久修改成功"),
                });
              } else {
                $q.notify({
                  type: "warning",
                  message: $t("OsParameter.永久修改失败"),
                });
              }
            });
        } else {
          $q.notify({ type: "positive", message: $t("OsParameter.修改成功") });
        }
      } else {
        $q.notify({ type: "warning", message: $t("OsParameter.永久修改失败") });
      }
    });
}
// 光标消失设置
function setConfiguration(data) {
  // const obj = {
  //   id: data.id,
  //   value: ''
  // }
  // if (data.type === 'bool') {
  //   obj.value = String(data.value)
  // } else {
  //   obj.value = data.value
  // }
  // api.post(useAPIStore().amrUrl + 'ros/call', [parameter.value, [obj]], { params: { service: '/config_center/set' } }).then(rs => {
  //   $q.notify({ type: 'positive', message: '设置成功' })
  // })
  // load()
}
const modified = computed(
  () => JSON.stringify(origin.value) !== JSON.stringify(parametersList.value)
);
// 重载配置
function resets() {
  parametersList.value = JSON.parse(JSON.stringify(origin.value));
  load();
}
// function reset () {
//   inputRef.value.resetValidation()
// }
</script>

<style lang="sass">
.my-sticky-header-table-black
  /* height or max-height is important */
  height: 310px

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    /* bg color is important for th; just specify one */
    background-color: rgba(0, 0, 0, 0.48)
    font-size: 16px

  thead tr th
    position: sticky
    z-index: 1
  thead tr:first-child th
    top: 0

  &.q-table--loading thead tr:last-child th
    top: 48px
</style>
<style lang="sass">
.my-sticky-header-table-white
  /* height or max-height is important */
  height: 310px

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    /* bg color is important for th; just specify one */
    background-color: rgb(255, 255, 255)
    font-size: 16px

  thead tr th
    position: sticky
    z-index: 1
  thead tr:first-child th
    top: 0

  &.q-table--loading thead tr:last-child th
    top: 48px
</style>
